/**
 * Created by 功振 on 2016/4/6.
 */
module.controller('ImageListController', function ($scope,$stateParams, $location, $rootScope, $cookies, $state,dockerRegisterService, notifications, $http, DeleteImageData, PublishImageData, cfpLoadingBar, ROLE,$filter,$mdDialog) {

    $stateParams.type = $stateParams.type || "private";
    $scope.isMarket = ($stateParams.type === 'private')?false:true;

    var role = $cookies.get("role");
    if (role == ROLE.OPERATOR) {
        $scope.isOperator = true;
    }
    dockerRegisterService.getImages($scope.isMarket).then(function (d) {
        var image=setImageColor(d.data.results);
        $scope.images = image;
    }).catch(function ( err ) {
        if( err && err.status == 404 ){
            alertify.error("[GetImageError]"+JSON.stringify( err.data )) ;
        }else{
            alertify.error(" Request timeout!" ) ;
        }
        console.log("response:"+JSON.stringify( err )) ;

    });
    $scope.ok=function (isMarket) {
        dockerRegisterService.getImages(isMarket).then(function (d) {
            var image=setImageColor(d.data.results);
            $scope.images = image;
        }).catch(function ( err ) {
            if( err && err.status == 404 ){
                alertify.error("[GetImageError]"+JSON.stringify( err.data )) ;
            }else{
                alertify.error(" Request timeout!" ) ;
            }
            console.log("response:"+JSON.stringify( err )) ;

        });
    }
    function setImageColor (images) {
        var image = images.slice();
        image.forEach(function (imgdata) {
            imgdata.AI = (imgdata.name.substring(0,2)).toUpperCase();
            imgdata.color='#'+getcolor();
        });
        return image;
    }
    var getcolor=function () {
        var colorlist=['49cb6f','01cad7','ef6293','ffc051','bbbbbb'];
        var dex=Math.floor(Math.random()*5);
        return colorlist[dex];
    };
    $scope.numPerPage = 12;
    $scope.currentPage = 1;
    $scope.currentpageprivate=1;

    $scope.change=function (page) {
        if($scope.images){
            var begin = ((page - 1) * $scope.numPerPage)
                , end = begin + $scope.numPerPage;
          var tmp = $scope.images.slice(begin, end);
            $scope.currentPageImages=tmp;
        }
    }

    $scope.searchPageHide=false;
  $scope.searchText="";
  $scope.$watch("images + currentPage", function() {
    var page=$scope.currentPage;
    if ($scope.images) {
            if($scope.isMarket){
                var begin = (($scope.currentPage - 1) * $scope.numPerPage)
                    , end = begin + $scope.numPerPage;
            }else{
                var begin = (($scope.currentpageprivate - 1) * $scope.numPerPage)
                    , end = begin + $scope.numPerPage;
            }
            if($scope.searchText === ""){
              $scope.currentPageImages = $scope.images.slice(begin, end);
            }else{
              $scope.currentPageImages = $filter('filter')($scope.images, {'name': $scope.searchText})
            }
        }
      $scope.searchClick=function () {
        /*       $scope.currentPageServices=utilService.searchObj(currentServices,$scope.services,$scope.searchText,'id')*/
        if ($scope.searchText == "") {
          $scope.searchPageHide=false;
          $scope.currentPageImages = $scope.images.slice(begin, end);

        } else {
          $scope.searchPageHide=true;
          $scope.currentPageImages = $filter('filter')($scope.images, {'name': $scope.searchText})
        }
      }


    });
    $scope.deleteImage = function(e,data,index){
        e.stopPropagation();
      $mdDialog.show({
        controller: function (data,$scope) {
          $scope.iName=data.name;
          $scope.ok=function () {
            dockerRegisterService.deleteImage(data).then(function(ret){

              $mdDialog.hide(ret);
            },function(err){
              //alertify.error('delete image ['+item.cfgMgrId+'] error:'+err.data.data);
              $mdDialog.cancel(err);
            });

          }
          $scope.cancel=function () {
            $mdDialog.cancel();
          }
        },
        templateUrl: 'delImage.html',
        parent: angular.element(document.body),
        targetEvent: e,
        clickOutsideToClose: true,
        fullscreen: true,// Only for -xs, -sm breakpoints.
        locals: {
          data:data,
          images:$scope.images
        }
      })
        .then(function(ret){
          if(ret.ret === true){
            /*var _idx = $scope.currentPageImages.indexOf(data);
            if(_idx > -1)
              $scope.currentPageImages.splice(index,1);*/
            $scope.images.splice(index,1);
            alertify.success(data.name + " repo delete succeeded");
          }else
            alertify.error(data.name + " repo delete failed");
        },function(err){
          if(err)
          alertify.error(data.name + " repo delete failed:"+err.data);

        });







        /*dockerRegisterService.deleteImage(data).then(function(ret){
            if(ret.ret === true){
                var _idx = $scope.currentPageImages.indexOf(data);
                if(_idx > -1)
                    $scope.currentPageImages.splice(_idx,1);
                alertify.success(data.name + " repo delete succeeded");
            }else
                alertify.error(data.name + " repo delete failed");
        }).catch(function(err){
            alertify.error(data.name + " repo delete failed:"+err.data);
        });*/

    }

});